package blog

import (
	"github.com/astaxie/beego/orm"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/util/gconv"
	"os"
	"time"
)

type Resources struct {
	Id       int
	Name     string    `orm:"size(255);unique"` // 文件名
	Md5      string    `orm:"size(64);unique"`  // 文件md5
	Path     string    `orm:"size(255)"`        // 路径
	Ext      string    // 扩展名
	Size     int64     // 大小
	NeedAuth bool      // 需要登录
	CreateAt time.Time `orm:"type(datetime);"` // 创建时间
}

func (o *Resources) TableName() string {
	return "blog_resources"
}

func CreateResource(name, md5, path string, size int64, ext string) error {
	resource := Resources{Name: name, Md5: md5, Path: path, Size: size, Ext: ext, CreateAt: time.Now()}
	_, err := orm.NewOrm().Insert(&resource)
	return err
}

func CheckResourceMd5(md5 string) bool {
	return orm.NewOrm().QueryTable(new(Resources)).Filter("md5", md5).Exist()
}

func GetResourceFromMd5(md5 string) (*Resources, error) {
	resource := Resources{}
	err := orm.NewOrm().QueryTable(new(Resources)).Filter("md5", md5).One(&resource)
	return &resource, err
}

func GetResourceFromName(name string) (*Resources, error) {
	resource := Resources{}
	err := orm.NewOrm().QueryTable(new(Resources)).Filter("name", name).One(&resource)
	return &resource, err
}

func GetResources(limit, page int) (all []Resources, total int64, err error) {
	if limit == 0 {
		limit = 10
	}
	if page == 0 {
		page = 1
	}
	qs := orm.NewOrm().QueryTable(new(Resources))
	total, _ = qs.Count()
	_, err = qs.Offset((page - 1) * limit).Limit(limit).All(&all)
	return
}

func ResourceCount() int64 {
	t, _ := orm.NewOrm().QueryTable(new(Resources)).Count()
	return t
}

func ResourceSizeTotal() int64 {
	var result []orm.Params
	_, _ = orm.NewOrm().Raw("select SUM(size) as total from blog_resources").Values(&result)
	return gconv.Int64(result[0]["total"])
}

func DeleteResourceFromId(id int) (err error) {
	resource := Resources{Id: id}
	err = orm.NewOrm().Read(&resource)
	if err != nil {
		return
	}
	err = os.Remove(resource.Path)
	if err != nil {
		glog.Errorf("remove file err: %s", err.Error())
	}
	_, err = orm.NewOrm().Delete(&resource)
	return
}
